import re
import time
import socket
from socket import gethostbyname, AF_INET, SOCK_DGRAM

# Unconnected ping text
packet_text = "01" + "0000000000000000" + "00ffff00fefefefefdfdfdfd12345678" + "0000000000000000"
# 设置连接超时
socket.setdefaulttimeout(5)


class BedrockStatusResponse:
    def __init__(self, data: bytes, latency: float):
        """解析数据包内容"""
        text = re.search(b"MCPE.+", data).group().decode()
        info_list = text.split(";")
        self.latency = latency
        self.motd = info_list[1]
        self.protocol = info_list[2]
        self.version = info_list[3]
        self.players_online = info_list[4]
        self.players_max = info_list[5]
        # self.??? = info_list[6]
        self.map = info_list[7]
        self.gamemode = info_list[8]
        # self.??? = info_list[9];
        # 以下项在非bds中可能不存在
        # self.port = int(info_list[10])
        # self.port6 = int(info_list[11])
        # self.??? = info_list[12];


class BedrockServer:
    @staticmethod
    def lookup(host: str) -> BedrockStatusResponse:
        # 地址的处理
        if re.search(":\\d{1,5}", host):
            ip = gethostbyname(host.split(":")[0])
            port = int(host.split(":")[1])
        else:
            ip = gethostbyname(host)
            port = 19132
        # Udp connect
        data_socket = socket.socket(AF_INET, SOCK_DGRAM)
        data_socket.connect((ip, port))
        # Unconnected ping
        start_time = time.time()
        data_socket.send(bytes.fromhex(packet_text))
        # recv data
        res = data_socket.recv(4096)
        end_time = time.time()
        # latency(ms)
        latency = round((end_time - start_time) * 1000, 2)
        return BedrockStatusResponse(res, latency)


if __name__ == '__main__':
    BedrockServer.lookup("127.0.0.1:19132")
